package com.ruix.app.ui.stratum.status;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.ruix.app.R;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.model.ClassDetail;
import com.ruix.app.model.Classes;
import com.ruix.app.model.User;
import com.ruix.app.ui.app.PhotoViewActivity;
import com.ruix.app.ui.stratum.setting.ClassShareActivity;
import com.ruix.app.ui.usercenter.UserConfigActivity;
import com.ruix.app.util.DateUtil;
import com.ruix.app.util.GlideUitl;
import com.ruix.app.util.LogUitl;
import com.ruix.app.util.QRCodeEncoder;
import com.ruix.app.util.ToastUtil;
import com.ruix.app.widget.TextViewVertical;
import com.ruix.app.widget.XCircleIndicator;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import me.iwf.photopicker.utils.PermissionsConstant;

import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

/**
 * Created by hadexs on 2017/4/28.
 */

public class ClassStatusActivity extends FragmentActivity {

    public static Intent newIntent(Context context, Classes classes, ClassDetail classDetail) {
        Intent intent = new Intent(context, ClassStatusActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("classes", classes);
        bundle.putSerializable("classDetail", classDetail);
        intent.putExtras(bundle);
        return intent;
    }

    private int colore = 0xFF333333;
    private ViewPager mViewPager;
    XCircleIndicator indicator;
    private ViewPaperAdapter vpAdapter;
    private ClassDetail classDetail;
    private Classes currentClasses;
    private String statues;
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        setContentView(R.layout.activity_class_status);
        indicator = (XCircleIndicator) findViewById(R.id.xCircleIndicator);
        mViewPager = (ViewPager) findViewById(R.id.vp_guide);

        if (classDetail == null || user == null || currentClasses == null) {
            finish();
            return;
        }
        statues = currentClasses.getStatus();
        if (currentClasses.isTeacherFriendCircle()){
            statues = "1"; //
            indicator.setVisibility(View.GONE);
        }

        ArrayList<View> views = new ArrayList<>();
        if ("1".equals(statues)) {
            View view1 = View.inflate(this, R.layout.layout_class_status_one, null);
            views.add(view1);
            initFirstView(view1);
        } else if ("2".equals(statues)) {
            View view1 = View.inflate(this, R.layout.layout_class_status_one, null);
            views.add(view1);
            View view2 = View.inflate(this, R.layout.layout_class_status_two, null);
            views.add(view2);
            initSecendView(view2);
            initFirstView(view1);
        } else if ("3".equals(statues)) {
            View view1 = View.inflate(this, R.layout.layout_class_status_one, null);
            views.add(view1);
            View view2 = View.inflate(this, R.layout.layout_class_status_two, null);
            views.add(view2);
            View view3 = View.inflate(this, R.layout.layout_class_status_three, null);
            views.add(view3);
            initFirstView(view1);
            initSecendView(view2);
            initThreeView(view3);
        } else {
            View view1 = View.inflate(this, R.layout.layout_class_status_one, null);
            views.add(view1);
            initFirstView(view1);
        }
        indicator.initData(views.size(), 0);// 设置总共的页数
        vpAdapter = new ViewPaperAdapter(views);
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                indicator.setCurrentPage(position);// 当页面切换的时候调用此方法改变被选中的圆点
            }
        });


        mViewPager.setOffscreenPageLimit(views.size());
        mViewPager.setAdapter(vpAdapter);
//        findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
        setCurrentPageWithState();

    }

    private void setCurrentPageWithState(){
        if ("1".equals(statues)) {
            indicator.setCurrentPage(0);// 设置当前所在页面
            mViewPager.setCurrentItem(0);
        } else if ("2".equals(statues)) {
            indicator.setCurrentPage(1);// 设置当前所在页面
            mViewPager.setCurrentItem(1);
        } else if ("3".equals(statues)) {
            indicator.setCurrentPage(2);// 设置当前所在页面
            mViewPager.setCurrentItem(2);
        } else {
            indicator.setCurrentPage(0);// 设置当前所在页面
            mViewPager.setCurrentItem(0);
        }

    }


//"张志明同学\n你已被《金融地产与资产管理领航班第一期上海班》让我们一起问道大咖导师，结伴精英学友，共同成长。\n百锐学堂   二零一七五月十日");

    private String buildFirstViewString() {
        StringBuffer sb = new StringBuffer();
        sb.append(user.getName() + "同学\n你已被《");
        sb.append(classDetail.getName());//让我们一起以实干家为师，以践行者为友，共同成长。
        sb.append("》录取\n让我们一起以实干家为师，以践行者为友，共同成长。\n");
        if (classDetail.isTeacherFriendCircle()){
            sb.append(classDetail.getClassOwnerName() + " ");
        } else {
            sb.append(classDetail.getOrganization() + " ");
        }

        String opentime = DateUtil.buildChinaTime(classDetail.getOpenTime());
        sb.append(opentime);
        return sb.toString();
    }

    private void initFirstView(View view) {
        TextViewVertical viewVertical = (TextViewVertical) view.findViewById(R.id.tvv_text);
        ImageView origanLogo = (ImageView) view.findViewById(R.id.iv_origan_logo);
        GlideUitl.showImageViewFitCenter(classDetail.getOrganizLogo(), origanLogo);
        viewVertical.setTextColor(colore);
        viewVertical.setLineWidth((int) getResources().getDimension(R.dimen.h_w_32));
        String shit = buildFirstViewString();
        viewVertical.setText(shit);
        final RelativeLayout containView = (RelativeLayout) view.findViewById(R.id.rl_comtain_view);
        view.findViewById(R.id.btn_sava_pic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                containView.setDrawingCacheEnabled(true);
//                containView.buildDrawingCache();  //启用DrawingCache并创建位图
//                Bitmap bitmap = Bitmap.createBitmap(containView.getDrawingCache()); //创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
//                containView.setDrawingCacheEnabled(false);
//
//                saveImageToGallery(getApplicationContext(), bitmap);

                mixAndsaveBitmapView(containView);
//                saveBitmapView(containView);
            }
        });
        view.findViewById(R.id.rl_cotain_root).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initSecendView(View view) {
        view.findViewById(R.id.rl_cotain_root).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    //"张志明同学\n你已被《金融地产与资产管理领航班第一期上海班》坚持学习十二天，通过考核予以结业。聚散有时，圈子常在。老同学，常联系。百锐学堂。二零一七五月十日");
    private String buildThreeViewString() {
        StringBuffer sb = new StringBuffer();
        sb.append(user.getName() + "同学\n你已在《");
        sb.append(classDetail.getName());
        sb.append("》\n坚持学习");
        String studyDay = DateUtil.studyDay(classDetail.getOpenTime(), classDetail.getCompleteTime());
        sb.append(studyDay);
        sb.append("天，通过考核予以结业。\n聚散有时，圈子常在。老同学，常联系。\n");

        if (classDetail.isTeacherFriendCircle()){
            sb.append(classDetail.getClassOwnerName() + " ");
        } else {
            sb.append(classDetail.getOrganization() + " ");
        }

        String completetime = DateUtil.buildChinaTime(classDetail.getCompleteTime());
        sb.append(completetime);
        return sb.toString();
    }

    private void initThreeView(View view) {
        TextViewVertical viewVertical = (TextViewVertical) view.findViewById(R.id.tvv_text);
        ImageView origanLogo = (ImageView) view.findViewById(R.id.iv_origan_logo);
        GlideUitl.showImageViewFitCenter(classDetail.getOrganizLogo(), origanLogo);

        viewVertical.setTextColor(colore);
        viewVertical.setLineWidth((int) getResources().getDimension(R.dimen.h_w_32));
        String shit = buildThreeViewString();
        viewVertical.setText(shit);
        viewVertical.setHasLastGraduate(true);

        final RelativeLayout containView = (RelativeLayout) view.findViewById(R.id.rl_comtain_view);
        view.findViewById(R.id.btn_sava_pic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mixAndsaveBitmapView(containView);
            }
        });
        view.findViewById(R.id.rl_cotain_root).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void savaBitmap() {

    }

    public void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "ruixue_pic");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
//        try {
////            MediaStore.Images.Media.insertImage(context.getContentResolver(),
////                    file.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        String path = file.getAbsolutePath();

        Uri uri = Uri.fromFile(file);

        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        ToastUtil.showNewSuccessMsg("保存成功");
    }


    private void saveBitmapView(View containView){
        if (checkWriteStoragePermission(this)){
            containView.setDrawingCacheEnabled(true);
            containView.buildDrawingCache();  //启用DrawingCache并创建位图
            Bitmap bitmap = Bitmap.createBitmap(containView.getDrawingCache()); //创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
            containView.setDrawingCacheEnabled(false);
            saveImageToGallery(getApplicationContext(), bitmap);
        }
    }

    private void mixAndsaveBitmapView(View containView){
        if (checkWriteStoragePermission(this)){
            containView.setDrawingCacheEnabled(true);
            containView.buildDrawingCache();  //启用DrawingCache并创建位图
            Bitmap bitmap = Bitmap.createBitmap(containView.getDrawingCache()); //创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
            containView.setDrawingCacheEnabled(false);
            Bitmap mixbitmap =  fotoMix(bitmap);
            saveImageToGallery(getApplicationContext(), mixbitmap);
        }
    }



    private String classcodeurl;
    //合成图片
    private Bitmap fotoMix(Bitmap bmp){
        if (classDetail.isTeacherFriendCircle()) { //
            classcodeurl = RuiXConstant.WX_TEACHE_FREAND_CIRECLE_SHARE + classDetail.getEncryptId();//&source=android&is_show_bottombar=1
        } else {
            classcodeurl = RuiXConstant.WX_CLASS_INFO_URL + classDetail.getEncryptId();
        }

       int qrcodeWidth =   BGAQRCodeUtil.dp2px(ClassStatusActivity.this, 58);
        int foregroundColor = 0xFFD55226;
       Bitmap qrcode = QRCodeEncoder.syncEncodeQRCode(classcodeurl, qrcodeWidth, foregroundColor ,Color.WHITE,null);
       Bitmap bitmapAdd =  BitmapFactory.decodeResource(getResources(),R.drawable.class_state_add_shit);
        int height = bitmapAdd.getHeight() +bmp.getHeight();
        Paint paint =new Paint();
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);

        Bitmap mixBitmap = Bitmap.createBitmap(bmp.getWidth(), height, bmp.getConfig());
        Canvas canvas = new Canvas(mixBitmap);

        int start =  (bmp.getWidth() - bitmapAdd.getWidth())/2;
        int  startX = start;
        int  startY = bmp.getHeight() - BGAQRCodeUtil.dp2px(ClassStatusActivity.this, 12);
        int  endX = startX +  BGAQRCodeUtil.dp2px(ClassStatusActivity.this, 122);
        int  endY = startY + BGAQRCodeUtil.dp2px(ClassStatusActivity.this, 188);
        Rect rectshit = new Rect(startX,startY,endX,endY); //计算下面边框区域


        RectF rectF = new RectF(0,0,bmp.getWidth(),endY);
        canvas.drawRect(rectF,paint); //画白色背景

        canvas.drawBitmap(bmp,0,0,null);//画上面部分
        canvas.drawBitmap(bitmapAdd,null,rectshit,null); //下面边框
        int qrcodex = (mixBitmap.getWidth() - qrcodeWidth)/2;
        int qrcodeY = bmp.getHeight() + BGAQRCodeUtil.dp2px(ClassStatusActivity.this, 30);
        canvas.drawBitmap(qrcode,qrcodex,qrcodeY,null); //二维码
        return mixBitmap;
    }

    //TODO 合成图片放到子线程
    private void fotoMix(final View containView){
        new AsyncTask<Void, View, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {

                return null;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                if (bitmap != null) {
                }
            }
        }.execute();
    }

    //todo

    private class ViewPaperAdapter extends PagerAdapter {
        private ArrayList<View> views;

        public ViewPaperAdapter(ArrayList<View> views) {
            this.views = views;
        }

        @Override
        public int getCount() {
            if (views != null) {
                return views.size();
            } else
                return 0;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return (arg0 == arg1);
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView(views.get(position));
        }

        @Override
        public Object instantiateItem(View container, int position) {
            ((ViewPager) container).addView(views.get(position), 0);
            return views.get(position);
        }

    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            currentClasses =  (Classes)intent.getSerializableExtra("classes");
            classDetail = (ClassDetail) intent.getSerializableExtra("classDetail");
        }
        user = UserManager.getCurrentUser();

    }

    //
    public static boolean checkWriteStoragePermission(Activity context) {
        if (Build.VERSION.SDK_INT >= 23) {
            int writeStoragePermissionState =
                    ContextCompat.checkSelfPermission(context, WRITE_EXTERNAL_STORAGE);
            if (writeStoragePermissionState != PackageManager.PERMISSION_GRANTED) {
                context.requestPermissions(PermissionsConstant.PERMISSIONS_EXTERNAL_WRITE,
                        PermissionsConstant.REQUEST_EXTERNAL_WRITE);
                return false;
            }
            return true;
        }
        return true;
    }



}
